//! # Core模块测试
//!
//! 为网关核心接口提供全面的测试覆盖，包括trait测试、Mock实现和集成测试。

#[cfg(test)]
mod tests {
    use super::super::*;
    use crate::core::{
        GatewayHandler, Middleware, GatewayServiceDiscoveryManager, LoadBalancer,
        GatewayRequest, GatewayResponse, GatewayContext, GatewayResult, GatewayError
    };
    // 使用rustcloud-core中的统一接口
    use rustcloud_core::{ServiceRegistry, ServiceInstance, ServiceWatcher};
    use async_trait::async_trait;
    use axum::http::{Method, Uri, StatusCode};
    use std::sync::Arc;
    use std::collections::HashMap;
    use std::time::SystemTime;
    use tokio::sync::Mutex;

    // =============================================================================
    // Mock 实现
    // =============================================================================

    /// Mock网关处理器，用于测试GatewayHandler trait
    pub struct MockGatewayHandler {
        pub name: String,
        pub should_succeed: bool,
        pub response_status: StatusCode,
        pub health_status: bool,
    }

    impl MockGatewayHandler {
        pub fn new(name: &str) -> Self {
            Self {
                name: name.to_string(),
                should_succeed: true,
                response_status: StatusCode::OK,
                health_status: true,
            }
        }

        pub fn with_failure(mut self) -> Self {
            self.should_succeed = false;
            self
        }

        pub fn with_status(mut self, status: StatusCode) -> Self {
            self.response_status = status;
            self
        }

        pub fn with_unhealthy(mut self) -> Self {
            self.health_status = false;
            self
        }
    }

    #[async_trait]
    impl GatewayHandler for MockGatewayHandler {
        async fn handle(&self, _request: GatewayRequest, _context: Arc<GatewayContext>) -> GatewayResult<GatewayResponse> {
            if !self.should_succeed {
                return Err(GatewayError::internal("模拟处理失败"));
            }

            let mut response = GatewayResponse::new(self.response_status);
            response.set_body(b"mock response".to_vec());
            Ok(response)
        }

        fn name(&self) -> &str {
            &self.name
        }

        async fn health_check(&self) -> bool {
            self.health_status
        }
    }

    /// Mock中间件，用于测试Middleware trait
    pub struct MockMiddleware {
        pub name: String,
        pub priority: i32,
        pub should_fail_before: bool,
        pub should_fail_after: bool,
        pub modify_request: bool,
        pub modify_response: bool,
        pub call_count: Arc<Mutex<usize>>,
    }

    impl MockMiddleware {
        pub fn new(name: &str) -> Self {
            Self {
                name: name.to_string(),
                priority: 100,
                should_fail_before: false,
                should_fail_after: false,
                modify_request: false,
                modify_response: false,
                call_count: Arc::new(Mutex::new(0)),
            }
        }

        pub fn with_priority(mut self, priority: i32) -> Self {
            self.priority = priority;
            self
        }

        pub fn with_before_failure(mut self) -> Self {
            self.should_fail_before = true;
            self
        }

        pub fn with_after_failure(mut self) -> Self {
            self.should_fail_after = true;
            self
        }

        pub fn with_request_modification(mut self) -> Self {
            self.modify_request = true;
            self
        }

        pub fn with_response_modification(mut self) -> Self {
            self.modify_response = true;
            self
        }

        pub async fn get_call_count(&self) -> usize {
            *self.call_count.lock().await
        }
    }

    #[async_trait]
    impl Middleware for MockMiddleware {
        async fn before_request(&self, mut request: GatewayRequest, _context: Arc<GatewayContext>) -> GatewayResult<GatewayRequest> {
            let mut count = self.call_count.lock().await;
            *count += 1;

            if self.should_fail_before {
                return Err(GatewayError::internal("模拟before_request失败"));
            }

            if self.modify_request {
                request.add_header("X-Mock-Middleware", &self.name);
            }

            Ok(request)
        }

        async fn after_response(&self, mut response: GatewayResponse, _context: Arc<GatewayContext>) -> GatewayResult<GatewayResponse> {
            if self.should_fail_after {
                return Err(GatewayError::internal("模拟after_response失败"));
            }

            if self.modify_response {
                response.add_header("X-Mock-Middleware-Response", &self.name);
            }

            Ok(response)
        }

        fn name(&self) -> &str {
            &self.name
        }

        fn priority(&self) -> i32 {
            self.priority
        }
    }

    /// Mock服务注册中心，符合rustcloud-core ServiceRegistry trait
    pub struct MockServiceRegistry {
        pub instances: Arc<Mutex<HashMap<String, Vec<ServiceInstance>>>>,
        pub should_fail: bool,
    }

    impl MockServiceRegistry {
        pub fn new() -> Self {
            Self {
                instances: Arc::new(Mutex::new(HashMap::new())),
                should_fail: false,
            }
        }

        pub fn with_failure(mut self) -> Self {
            self.should_fail = true;
            self
        }

        pub async fn add_instance(&self, service_name: &str, instance: ServiceInstance) {
            let mut instances = self.instances.lock().await;
            instances.entry(service_name.to_string())
                .or_insert_with(Vec::new)
                .push(instance);
        }

        pub async fn get_instance_count(&self, service_name: &str) -> usize {
            let instances = self.instances.lock().await;
            instances.get(service_name).map(|v| v.len()).unwrap_or(0)
        }
    }

    #[async_trait]
    impl ServiceRegistry for MockServiceRegistry {
        async fn register(&self, instance: ServiceInstance) -> rustcloud_core::ServiceResult<()> {
            if self.should_fail {
                return Err(rustcloud_core::ServiceError::RegistryError("模拟注册失败".to_string()));
            }

            let service_name = instance.service_id.clone();
            self.add_instance(&service_name, instance).await;
            Ok(())
        }

        async fn deregister(&self, instance: &ServiceInstance) -> rustcloud_core::ServiceResult<()> {
            if self.should_fail {
                return Err(rustcloud_core::ServiceError::RegistryError("模拟注销失败".to_string()));
            }

            let mut instances = self.instances.lock().await;
            if let Some(service_instances) = instances.get_mut(&instance.service_id) {
                service_instances.retain(|i| i.service_id != instance.service_id || i.host != instance.host || i.port != instance.port);
            }
            Ok(())
        }

        async fn discover(&self, service_name: &str) -> rustcloud_core::ServiceResult<Vec<ServiceInstance>> {
            if self.should_fail {
                return Err(rustcloud_core::ServiceError::ServiceNotFound(service_name.to_string()));
            }

            let instances = self.instances.lock().await;
            Ok(instances.get(service_name).cloned().unwrap_or_default())
        }

        async fn health_check(&self, service_name: &str) -> rustcloud_core::ServiceResult<Vec<ServiceInstance>> {
            let instances = self.discover(service_name).await?;
            Ok(instances.into_iter().filter(|i| i.healthy).collect())
        }

        async fn list_services(&self) -> rustcloud_core::ServiceResult<Vec<String>> {
            let instances = self.instances.lock().await;
            Ok(instances.keys().cloned().collect())
        }

        async fn watch(&self, _service_name: &str) -> rustcloud_core::ServiceResult<Box<dyn ServiceWatcher + Send>> {
            // Mock实现，返回一个简单的watcher
            Err(rustcloud_core::ServiceError::NotImplemented("模拟注册中心不支持watch功能".to_string()))
        }
    }

    /// Mock负载均衡器，用于测试LoadBalancer trait
    pub struct MockLoadBalancer {
        pub selection_strategy: LoadBalancerStrategy,
        pub should_fail: bool,
        pub call_reports: Arc<Mutex<Vec<(ServiceInstance, bool, u64)>>>,
    }

    #[derive(Debug, Clone)]
    pub enum LoadBalancerStrategy {
        RoundRobin,
        Random,
        First,
        Last,
        None,
    }

    impl MockLoadBalancer {
        pub fn new(strategy: LoadBalancerStrategy) -> Self {
            Self {
                selection_strategy: strategy,
                should_fail: false,
                call_reports: Arc::new(Mutex::new(Vec::new())),
            }
        }

        pub fn with_failure(mut self) -> Self {
            self.should_fail = true;
            self
        }

        pub async fn get_report_count(&self) -> usize {
            self.call_reports.lock().await.len()
        }

        pub async fn get_last_report(&self) -> Option<(ServiceInstance, bool, u64)> {
            self.call_reports.lock().await.last().cloned()
        }
    }

    #[async_trait]
    impl LoadBalancer for MockLoadBalancer {
        async fn select(&self, service_name: &str, instances: &[ServiceInstance], _context: Arc<GatewayContext>) -> GatewayResult<Option<ServiceInstance>> {
            if self.should_fail {
                return Err(GatewayError::load_balance("模拟负载均衡失败", service_name));
            }

            if instances.is_empty() {
                return Ok(None);
            }

            let selected = match self.selection_strategy {
                LoadBalancerStrategy::RoundRobin => instances.first().cloned(),
                LoadBalancerStrategy::Random => instances.get(instances.len() / 2).cloned(),
                LoadBalancerStrategy::First => instances.first().cloned(),
                LoadBalancerStrategy::Last => instances.last().cloned(),
                LoadBalancerStrategy::None => None,
            };

            Ok(selected)
        }

        async fn report(&self, instance: &ServiceInstance, success: bool, response_time: u64) {
            let mut reports = self.call_reports.lock().await;
            reports.push((instance.clone(), success, response_time));
        }
    }

    // =============================================================================
    // ServiceInstance 测试
    // =============================================================================

    #[test]
    fn test_service_instance_creation() {
        let instance = ServiceInstance::new(
            "test-service",
            "localhost",
            8080,
            "http"
        );

        assert_eq!(instance.service_name, "test-service");
        assert_eq!(instance.host, "localhost");
        assert_eq!(instance.port, 8080);
        assert_eq!(instance.id, "test-service:localhost:8080");
        assert_eq!(instance.weight, 100);
        assert!(instance.healthy);
        assert!(instance.metadata.is_empty());
    }

    #[test]
    fn test_service_instance_address() {
        let instance = ServiceInstance::new(
            "test-service",
            "127.0.0.1",
            9090,
            "http"
        );

        // ServiceInstance的address()方法返回scheme://host:port格式
        assert_eq!(instance.address(), "http://127.0.0.1:9090");
    }

    #[test]
    fn test_service_instance_with_metadata() {
        let mut instance = ServiceInstance::new(
            "test-service",
            "localhost",
            8080,
            "http"
        );

        instance.metadata.insert("version".to_string(), "1.0.0".to_string());
        instance.metadata.insert("region".to_string(), "us-east-1".to_string());

        assert_eq!(instance.metadata.get("version"), Some(&"1.0.0".to_string()));
        assert_eq!(instance.metadata.get("region"), Some(&"us-east-1".to_string()));
    }

    #[test]
    fn test_service_instance_unhealthy() {
        let mut instance = ServiceInstance::new(
            "test-service",
            "localhost",
            8080,
            "http"
        );

        instance.healthy = false;
        assert!(!instance.healthy);
    }

    #[test]
    fn test_service_instance_custom_weight() {
        let mut instance = ServiceInstance::new(
            "test-service",
            "localhost",
            8080,
            "http"
        );

        instance.weight = 50.0;  // weight字段是f64类型
        assert_eq!(instance.weight, 50.0);
    }

    // =============================================================================
    // GatewayHandler 测试
    // =============================================================================

    #[tokio::test]
    async fn test_gateway_handler_success() {
        let handler = MockGatewayHandler::new("test-handler");
        let request = create_test_request();
        let context = create_test_context();

        let result = handler.handle(request, context).await;
        assert!(result.is_ok());

        let response = result.unwrap();
        assert_eq!(response.status, StatusCode::OK);
        assert_eq!(response.body, b"mock response");
    }

    #[tokio::test]
    async fn test_gateway_handler_failure() {
        let handler = MockGatewayHandler::new("test-handler").with_failure();
        let request = create_test_request();
        let context = create_test_context();

        let result = handler.handle(request, context).await;
        assert!(result.is_err());

        if let Err(GatewayError::Internal { message }) = result {
            assert_eq!(message, "模拟处理失败");
        } else {
            panic!("Expected Internal error");
        }
    }

    #[tokio::test]
    async fn test_gateway_handler_custom_status() {
        let handler = MockGatewayHandler::new("test-handler")
            .with_status(StatusCode::CREATED);
        let request = create_test_request();
        let context = create_test_context();

        let result = handler.handle(request, context).await;
        assert!(result.is_ok());

        let response = result.unwrap();
        assert_eq!(response.status, StatusCode::CREATED);
    }

    #[tokio::test]
    async fn test_gateway_handler_name() {
        let handler = MockGatewayHandler::new("my-test-handler");
        assert_eq!(handler.name(), "my-test-handler");
    }

    #[tokio::test]
    async fn test_gateway_handler_health_check_healthy() {
        let handler = MockGatewayHandler::new("test-handler");
        assert!(handler.health_check().await);
    }

    #[tokio::test]
    async fn test_gateway_handler_health_check_unhealthy() {
        let handler = MockGatewayHandler::new("test-handler").with_unhealthy();
        assert!(!handler.health_check().await);
    }

    // =============================================================================
    // Middleware 测试
    // =============================================================================

    #[tokio::test]
    async fn test_middleware_before_request_success() {
        let middleware = MockMiddleware::new("test-middleware");
        let request = create_test_request();
        let context = create_test_context();

        let result = middleware.before_request(request, context).await;
        assert!(result.is_ok());
        assert_eq!(middleware.get_call_count().await, 1);
    }

    #[tokio::test]
    async fn test_middleware_before_request_failure() {
        let middleware = MockMiddleware::new("test-middleware").with_before_failure();
        let request = create_test_request();
        let context = create_test_context();

        let result = middleware.before_request(request, context).await;
        assert!(result.is_err());
        assert_eq!(middleware.get_call_count().await, 1);
    }

    #[tokio::test]
    async fn test_middleware_before_request_modification() {
        let middleware = MockMiddleware::new("test-middleware").with_request_modification();
        let request = create_test_request();
        let context = create_test_context();

        let result = middleware.before_request(request, context).await;
        assert!(result.is_ok());

        let modified_request = result.unwrap();
        assert!(modified_request.headers.contains_key("x-mock-middleware"));
    }

    #[tokio::test]
    async fn test_middleware_after_response_success() {
        let middleware = MockMiddleware::new("test-middleware");
        let response = create_test_response();
        let context = create_test_context();

        let result = middleware.after_response(response, context).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_middleware_after_response_failure() {
        let middleware = MockMiddleware::new("test-middleware").with_after_failure();
        let response = create_test_response();
        let context = create_test_context();

        let result = middleware.after_response(response, context).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_middleware_after_response_modification() {
        let middleware = MockMiddleware::new("test-middleware").with_response_modification();
        let response = create_test_response();
        let context = create_test_context();

        let result = middleware.after_response(response, context).await;
        assert!(result.is_ok());

        let modified_response = result.unwrap();
        assert!(modified_response.headers.contains_key("x-mock-middleware-response"));
    }

    #[tokio::test]
    async fn test_middleware_name() {
        let middleware = MockMiddleware::new("my-test-middleware");
        assert_eq!(middleware.name(), "my-test-middleware");
    }

    #[tokio::test]
    async fn test_middleware_priority_default() {
        let middleware = MockMiddleware::new("test-middleware");
        assert_eq!(middleware.priority(), 100);
    }

    #[tokio::test]
    async fn test_middleware_priority_custom() {
        let middleware = MockMiddleware::new("test-middleware").with_priority(50);
        assert_eq!(middleware.priority(), 50);
    }

    // =============================================================================
    // GatewayServiceDiscoveryManager 测试
    // =============================================================================

    #[tokio::test]
    async fn test_gateway_service_discovery_manager_discover_empty() {
        let registry = Arc::new(MockServiceRegistry::new());
        let manager = GatewayServiceDiscoveryManager::new(registry);
        let result = manager.discover_service("nonexistent-service").await;
        
        assert!(result.is_ok());
        let instances = result.unwrap();
        assert!(instances.is_empty());
    }

    #[tokio::test]
    async fn test_gateway_service_discovery_manager_discover_with_cache() {
        let registry = Arc::new(MockServiceRegistry::new());
        let manager = GatewayServiceDiscoveryManager::new(registry.clone());
        
        let instance = ServiceInstance::new("test-service", "localhost", 8080, "http");
        registry.add_instance("test-service", instance).await;

        // 第一次发现
        let result1 = manager.discover_service("test-service").await;
        assert!(result1.is_ok());
        let instances1 = result1.unwrap();
        assert_eq!(instances1.len(), 1);

        // 第二次发现应该使用缓存
        let result2 = manager.discover_service("test-service").await;
        assert!(result2.is_ok());
        let instances2 = result2.unwrap();
        assert_eq!(instances2.len(), 1);
    }

    #[tokio::test]
    async fn test_gateway_service_discovery_manager_clear_cache() {
        let registry = Arc::new(MockServiceRegistry::new());
        let manager = GatewayServiceDiscoveryManager::new(registry.clone());
        
        let instance = ServiceInstance::new("test-service", "localhost", 8080, "http");
        registry.add_instance("test-service", instance).await;

        // 发现服务（填充缓存）
        let _ = manager.discover_service("test-service").await;
        
        // 清除缓存
        manager.clear_cache().await;
        
        // 再次发现应该从注册中心获取
        let result = manager.discover_service("test-service").await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_gateway_service_discovery_manager_registry_failure() {
        let registry = Arc::new(MockServiceRegistry::new().with_failure());
        let manager = GatewayServiceDiscoveryManager::new(registry);
        
        let result = manager.discover_service("test-service").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_gateway_service_discovery_manager_health_check() {
        let registry = Arc::new(MockServiceRegistry::new());
        let manager = GatewayServiceDiscoveryManager::new(registry.clone());
        
        let mut instance = ServiceInstance::new("test-service", "localhost", 8080, "http");
        // 添加额外的scheme参数
        registry.add_instance("test-service", instance).await;

        let health_instances = registry.health_check("test-service").await.unwrap();
        assert_eq!(health_instances.len(), 1);
    }

    #[tokio::test]
    async fn test_gateway_service_discovery_manager_weight_test() {
        let registry = Arc::new(MockServiceRegistry::new());
        let manager = GatewayServiceDiscoveryManager::new(registry);
        
        let mut instance = ServiceInstance::new("test-service", "localhost", 8080, "http");
        instance.weight = 2.0;  // weight是f64类型
        
        assert_eq!(instance.weight, 2.0);
    }
    
    #[tokio::test]
    async fn test_gateway_service_discovery_manager_another_test() {
        let mut instance = ServiceInstance::new("test-service", "localhost", 8080, "http");
        // 添加额外的scheme参数
        instance.weight = 50.0;  // weight是f64类型
        assert_eq!(instance.weight, 50.0);
    }

    // =============================================================================
    // LoadBalancer 测试
    // =============================================================================

    #[tokio::test]
    async fn test_load_balancer_select_empty_instances() {
        let balancer = MockLoadBalancer::new(LoadBalancerStrategy::RoundRobin);
        let context = create_test_context();

        let result = balancer.select("test-service", &[], context).await;
        assert!(result.is_ok());
        assert!(result.unwrap().is_none());
    }

    #[tokio::test]
    async fn test_load_balancer_select_first_strategy() {
        let balancer = MockLoadBalancer::new(LoadBalancerStrategy::First);
        let instances = vec![
            ServiceInstance::new("test-service", "localhost", 8080, "http"),
            ServiceInstance::new("test-service", "localhost", 8081, "http"),
            ServiceInstance::new("test-service", "localhost", 8082, "http"),
        ];
        let context = create_test_context();

        let result = balancer.select("test-service", &instances, context).await;
        assert!(result.is_ok());

        let selected = result.unwrap().unwrap();
        assert_eq!(selected.service_id, instances[0].service_id);
    }

    #[tokio::test]
    async fn test_load_balancer_select_last_strategy() {
        let balancer = MockLoadBalancer::new(LoadBalancerStrategy::Last);
        let instances = create_test_instances();
        let context = create_test_context();

        let result = balancer.select("test-service", &instances, context).await;
        assert!(result.is_ok());

        let selected = result.unwrap().unwrap();
        assert_eq!(selected.service_id, instances.last().unwrap().service_id);
    }

    #[tokio::test]
    async fn test_load_balancer_select_none_strategy() {
        let balancer = MockLoadBalancer::new(LoadBalancerStrategy::None);
        let instances = create_test_instances();
        let context = create_test_context();

        let result = balancer.select("test-service", &instances, context).await;
        assert!(result.is_ok());
        assert!(result.unwrap().is_none());
    }

    #[tokio::test]
    async fn test_load_balancer_select_failure() {
        let balancer = MockLoadBalancer::new(LoadBalancerStrategy::RoundRobin).with_failure();
        let instances = create_test_instances();
        let context = create_test_context();

        let result = balancer.select("test-service", &instances, context).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_load_balancer_report_result() {
        let balancer = MockLoadBalancer::new(LoadBalancerStrategy::RoundRobin);
        let instance = ServiceInstance::new("test-service", "localhost", 8080, "http");

        balancer.report(&instance, true, 150).await;

        let reports = balancer.get_reports().await;
        assert_eq!(reports.len(), 1);

        let last_report = &reports[0];
        assert_eq!(last_report.0.service_id, instance.service_id);
        assert!(last_report.1);
        assert_eq!(last_report.2, 150);
    }

    #[tokio::test]
    async fn test_load_balancer_report_multiple_results() {
        let balancer = MockLoadBalancer::new(LoadBalancerStrategy::RoundRobin);
        let instances = create_test_instances();

        for instance in &instances {
            balancer.report(instance, true, 100).await;
        }

        let reports = balancer.get_reports().await;
        assert_eq!(reports.len(), instances.len());

        let last_report = &reports[0];
        assert_eq!(last_report.0.service_id, instances[0].service_id);
        assert!(last_report.1);
        assert_eq!(last_report.2, 100);
    }
    
    #[tokio::test]
    async fn test_load_balancer_report() {
        let balancer = MockLoadBalancer::new(LoadBalancerStrategy::RoundRobin);
        let instance = create_test_instances()[0].clone();

        balancer.report(&instance, true, 100).await;
        assert_eq!(balancer.get_report_count().await, 1);

        let last_report = balancer.get_last_report().await.unwrap();
        assert_eq!(last_report.0.id, instance.id);
        assert!(last_report.1);
        assert_eq!(last_report.2, 100);
    }

    #[tokio::test]
    async fn test_load_balancer_multiple_reports() {
        let balancer = MockLoadBalancer::new(LoadBalancerStrategy::RoundRobin);
        let instances = create_test_instances();

        balancer.report(&instances[0], true, 100).await;
        balancer.report(&instances[1], false, 200).await;
        balancer.report(&instances[0], true, 50).await;

        assert_eq!(balancer.get_report_count().await, 3);

        let last_report = balancer.get_last_report().await.unwrap();
        assert_eq!(last_report.0.id, instances[0].id);
        assert!(last_report.1);
        assert_eq!(last_report.2, 50);
    }

    // =============================================================================
    // 辅助函数
    // =============================================================================

    fn create_test_request() -> GatewayRequest {
        let uri = "http://localhost:8080/test".parse::<Uri>().unwrap();
        GatewayRequest::new(Method::GET, uri)
    }

    fn create_test_response() -> GatewayResponse {
        GatewayResponse::new(StatusCode::OK)
    }

    fn create_test_context() -> Arc<GatewayContext> {
        Arc::new(GatewayContext::new("test-request-id".to_string()))
    }

    fn create_test_instances() -> Vec<ServiceInstance> {
        vec![
            ServiceInstance::new("test-service", "localhost", 8080, "http"),
            ServiceInstance::new("test-service", "localhost", 8081, "http"),
            ServiceInstance::new("test-service", "localhost", 8082, "http"),
        ]
    }

    // =============================================================================
    // Types 模块测试
    // =============================================================================

    #[test]
    fn test_gateway_request_creation() {
        let uri = "http://localhost:8080/api/users?page=1&size=10".parse::<Uri>().unwrap();
        let request = GatewayRequest::new(Method::GET, uri);

        assert_eq!(request.method, Method::GET);
        assert_eq!(request.path, "/api/users");
        assert_eq!(request.query_params.get("page"), Some(&"1".to_string()));
        assert_eq!(request.query_params.get("size"), Some(&"10".to_string()));
        assert!(request.body.is_empty());
        assert!(request.client_ip.is_none());
        assert!(request.target_service.is_none());
        assert!(!request.id.is_empty());
    }

    #[test]
    fn test_gateway_request_with_body() {
        let uri = "http://localhost:8080/api/users".parse::<Uri>().unwrap();
        let mut request = GatewayRequest::new(Method::POST, uri);
        let body_data = b"{\"name\":\"test\"}".to_vec();
        
        request.set_body(body_data.clone());
        assert_eq!(request.body, body_data);
    }

    #[test]
    fn test_gateway_request_set_target_service() {
        let uri = "http://localhost:8080/api/users".parse::<Uri>().unwrap();
        let mut request = GatewayRequest::new(Method::GET, uri);
        
        request.set_target_service("user-service".to_string());
        assert_eq!(request.target_service, Some("user-service".to_string()));
    }

    #[test]
    fn test_gateway_request_set_client_ip() {
        let uri = "http://localhost:8080/api/users".parse::<Uri>().unwrap();
        let mut request = GatewayRequest::new(Method::GET, uri);
        
        request.set_client_ip("192.168.1.100".to_string());
        assert_eq!(request.client_ip, Some("192.168.1.100".to_string()));
    }

    #[test]
    fn test_gateway_request_add_header() {
        let uri = "http://localhost:8080/api/users".parse::<Uri>().unwrap();
        let mut request = GatewayRequest::new(Method::GET, uri);
        
        request.add_header("Authorization", "Bearer token123");
        request.add_header("Content-Type", "application/json");
        
        assert!(request.headers.contains_key("authorization"));
        assert!(request.headers.contains_key("content-type"));
    }

    #[test]
    fn test_gateway_request_parse_query_params_empty() {
        let uri = "http://localhost:8080/api/users".parse::<Uri>().unwrap();
        let request = GatewayRequest::new(Method::GET, uri);
        
        assert!(request.query_params.is_empty());
    }

    #[test]
    fn test_gateway_request_parse_query_params_single() {
        let uri = "http://localhost:8080/api/users?id=123".parse::<Uri>().unwrap();
        let request = GatewayRequest::new(Method::GET, uri);
        
        assert_eq!(request.query_params.len(), 1);
        assert_eq!(request.query_params.get("id"), Some(&"123".to_string()));
    }

    #[test]
    fn test_gateway_request_parse_query_params_multiple() {
        let uri = "http://localhost:8080/api/users?page=1&size=10&sort=name".parse::<Uri>().unwrap();
        let request = GatewayRequest::new(Method::GET, uri);
        
        assert_eq!(request.query_params.len(), 3);
        assert_eq!(request.query_params.get("page"), Some(&"1".to_string()));
        assert_eq!(request.query_params.get("size"), Some(&"10".to_string()));
        assert_eq!(request.query_params.get("sort"), Some(&"name".to_string()));
    }

    #[test]
    fn test_gateway_request_parse_query_params_special_chars() {
        let uri = "http://localhost:8080/api/search?q=hello%20world&type=user".parse::<Uri>().unwrap();
        let request = GatewayRequest::new(Method::GET, uri);
        
        // 注意：我们的简化实现不做 URL 解码
        assert_eq!(request.query_params.get("q"), Some(&"hello%20world".to_string()));
        assert_eq!(request.query_params.get("type"), Some(&"user".to_string()));
    }

    #[test]
    fn test_gateway_response_creation() {
        let response = GatewayResponse::new(StatusCode::OK);
        
        assert_eq!(response.status, StatusCode::OK);
        assert!(response.body.is_empty());
        assert_eq!(response.processing_time, 0);
        assert!(response.service_instance.is_none());
    }

    #[test]
    fn test_gateway_response_ok() {
        let response = GatewayResponse::ok();
        assert_eq!(response.status, StatusCode::OK);
    }

    #[test]
    fn test_gateway_response_error() {
        let response = GatewayResponse::error(StatusCode::BAD_REQUEST, "Invalid input");
        
        assert_eq!(response.status, StatusCode::BAD_REQUEST);
        assert_eq!(response.body, b"Invalid input");
        assert!(response.headers.contains_key("content-type"));
    }

    #[test]
    fn test_gateway_response_add_header() {
        let mut response = GatewayResponse::new(StatusCode::OK);
        
        response.add_header("X-Request-ID", "req-123");
        response.add_header("Content-Type", "application/json");
        
        assert!(response.headers.contains_key("x-request-id"));
        assert!(response.headers.contains_key("content-type"));
    }

    #[test]
    fn test_gateway_response_set_body() {
        let mut response = GatewayResponse::new(StatusCode::OK);
        let body_data = b"{\"status\":\"success\"}".to_vec();
        
        response.set_body(body_data.clone());
        assert_eq!(response.body, body_data);
    }

    #[test]
    fn test_gateway_response_set_processing_time() {
        let mut response = GatewayResponse::new(StatusCode::OK);
        
        response.set_processing_time(150);
        assert_eq!(response.processing_time, 150);
    }

    #[test]
    fn test_gateway_response_set_service_instance() {
        let mut response = GatewayResponse::new(StatusCode::OK);
        
        response.set_service_instance("localhost:8080".to_string());
        assert_eq!(response.service_instance, Some("localhost:8080".to_string()));
    }

    #[test]
    fn test_gateway_context_creation() {
        let context = GatewayContext::new("req-123".to_string());
        
        assert_eq!(context.request_id, "req-123");
        assert!(context.auth_info.is_none());
        assert!(context.rate_limit_info.is_none());
        assert!(context.route_info.is_none());
        assert!(context.attributes.is_empty());
    }

    #[test]
    fn test_gateway_context_add_attribute() {
        let mut context = GatewayContext::new("req-123".to_string());
        
        context.add_attribute("user_id".to_string(), "user-456".to_string());
        context.add_attribute("session_id".to_string(), "sess-789".to_string());
        
        assert_eq!(context.get_attribute("user_id"), Some(&"user-456".to_string()));
        assert_eq!(context.get_attribute("session_id"), Some(&"sess-789".to_string()));
        assert_eq!(context.get_attribute("nonexistent"), None);
    }

    #[test]
    fn test_gateway_context_elapsed_time() {
        let context = GatewayContext::new("req-123".to_string());
        
        // 等待一小段时间
        std::thread::sleep(std::time::Duration::from_millis(1));
        
        let elapsed = context.elapsed_time();
        assert!(elapsed.as_millis() > 0);
    }

    #[test]
    fn test_auth_info_creation() {
        let mut attributes = HashMap::new();
        attributes.insert("department".to_string(), "engineering".to_string());
        
        let auth_info = AuthInfo {
            user_id: "user-123".to_string(),
            username: Some("john_doe".to_string()),
            roles: vec!["admin".to_string(), "user".to_string()],
            permissions: vec!["read".to_string(), "write".to_string()],
            auth_type: "JWT".to_string(),
            attributes,
        };
        
        assert_eq!(auth_info.user_id, "user-123");
        assert_eq!(auth_info.username, Some("john_doe".to_string()));
        assert_eq!(auth_info.roles.len(), 2);
        assert_eq!(auth_info.permissions.len(), 2);
        assert_eq!(auth_info.auth_type, "JWT");
        assert_eq!(auth_info.attributes.get("department"), Some(&"engineering".to_string()));
    }

    #[test]
    fn test_rate_limit_info_creation() {
        let reset_time = SystemTime::now() + std::time::Duration::from_secs(60);
        
        let rate_limit_info = RateLimitInfo {
            limited: true,
            remaining: 45,
            reset_time,
            rule_id: Some("rule-123".to_string()),
        };
        
        assert!(rate_limit_info.limited);
        assert_eq!(rate_limit_info.remaining, 45);
        assert_eq!(rate_limit_info.rule_id, Some("rule-123".to_string()));
    }

    #[test]
    fn test_route_info_creation() {
        let transform_rules = vec![
            TransformRule {
                rule_type: TransformType::PathRewrite,
                source: "/old".to_string(),
                target: "/new".to_string(),
                value: Some("/api/v2/new".to_string()),
            },
            TransformRule {
                rule_type: TransformType::AddHeader,
                source: "X-Version".to_string(),
                target: "X-Version".to_string(),
                value: Some("2.0".to_string()),
            },
        ];
        
        let route_info = RouteInfo {
            id: "route-123".to_string(),
            target_service: "user-service".to_string(),
            path_rewrite: Some("/api/v2/users".to_string()),
            transform_rules,
        };
        
        assert_eq!(route_info.id, "route-123");
        assert_eq!(route_info.target_service, "user-service");
        assert_eq!(route_info.path_rewrite, Some("/api/v2/users".to_string()));
        assert_eq!(route_info.transform_rules.len(), 2);
    }

    #[test]
    fn test_transform_rule_types() {
        let add_header = TransformRule {
            rule_type: TransformType::AddHeader,
            source: "X-Custom".to_string(),
            target: "X-Custom".to_string(),
            value: Some("custom-value".to_string()),
        };
        
        let remove_header = TransformRule {
            rule_type: TransformType::RemoveHeader,
            source: "X-Old-Header".to_string(),
            target: "X-Old-Header".to_string(),
            value: None,
        };
        
        let modify_header = TransformRule {
            rule_type: TransformType::ModifyHeader,
            source: "User-Agent".to_string(),
            target: "User-Agent".to_string(),
            value: Some("Gateway/1.0".to_string()),
        };
        
        let path_rewrite = TransformRule {
            rule_type: TransformType::PathRewrite,
            source: "/api/v1".to_string(),
            target: "/api/v2".to_string(),
            value: Some("/api/v2".to_string()),
        };
        
        let add_query_param = TransformRule {
            rule_type: TransformType::AddQueryParam,
            source: "version".to_string(),
            target: "version".to_string(),
            value: Some("2.0".to_string()),
        };
        
        // 简单验证数据结构
        assert_eq!(add_header.source, "X-Custom");
        assert_eq!(remove_header.value, None);
        assert_eq!(modify_header.value, Some("Gateway/1.0".to_string()));
        assert_eq!(path_rewrite.target, "/api/v2");
        assert_eq!(add_query_param.source, "version");
    }

    #[test]
    fn test_gateway_metrics_creation() {
        let mut service_health = HashMap::new();
        service_health.insert("user-service".to_string(), true);
        service_health.insert("order-service".to_string(), false);
        
        let metrics = GatewayMetrics {
            total_requests: 1000,
            successful_requests: 950,
            failed_requests: 50,
            avg_response_time: 125.5,
            active_connections: 25,
            rate_limited_requests: 10,
            auth_failed_requests: 5,
            service_health,
        };
        
        assert_eq!(metrics.total_requests, 1000);
        assert_eq!(metrics.successful_requests, 950);
        assert_eq!(metrics.failed_requests, 50);
        assert_eq!(metrics.avg_response_time, 125.5);
        assert_eq!(metrics.active_connections, 25);
        assert_eq!(metrics.rate_limited_requests, 10);
        assert_eq!(metrics.auth_failed_requests, 5);
        assert_eq!(metrics.service_health.get("user-service"), Some(&true));
        assert_eq!(metrics.service_health.get("order-service"), Some(&false));
    }

    #[test]
    fn test_gateway_metrics_calculations() {
        let metrics = GatewayMetrics {
            total_requests: 1000,
            successful_requests: 950,
            failed_requests: 50,
            avg_response_time: 125.5,
            active_connections: 25,
            rate_limited_requests: 10,
            auth_failed_requests: 5,
            service_health: HashMap::new(),
        };
        
        // 验证总数一致性
        assert_eq!(metrics.successful_requests + metrics.failed_requests, metrics.total_requests);
        
        // 计算成功率
        let success_rate = metrics.successful_requests as f64 / metrics.total_requests as f64;
        assert_eq!(success_rate, 0.95);
        
        // 计算失败率
        let failure_rate = metrics.failed_requests as f64 / metrics.total_requests as f64;
        assert_eq!(failure_rate, 0.05);
    }

    // =============================================================================
    // Errors 模块测试
    // =============================================================================

    #[test]
    fn test_gateway_error_authentication() {
        let error = GatewayError::authentication("认证失败");
        
        assert_eq!(error.status_code(), StatusCode::UNAUTHORIZED);
        assert_eq!(error.error_code(), "GATEWAY_AUTH_ERROR");
        assert_eq!(error.message(), "认证失败");
        assert!(!error.is_retryable());
        
        match error {
            GatewayError::Authentication { message, code } => {
                assert_eq!(message, "认证失败");
                assert_eq!(code, "AUTH_FAILED");
            },
            _ => panic!("Expected Authentication error"),
        }
    }

    #[test]
    fn test_gateway_error_authorization() {
        let error = GatewayError::authorization("没有权限");
        
        assert_eq!(error.status_code(), StatusCode::FORBIDDEN);
        assert_eq!(error.error_code(), "GATEWAY_AUTHZ_ERROR");
        assert!(!error.is_retryable());
        
        match error {
            GatewayError::Authorization { message, required_permission } => {
                assert_eq!(message, "没有权限");
                assert_eq!(required_permission, None);
            },
            _ => panic!("Expected Authorization error"),
        }
    }

    #[test]
    fn test_gateway_error_rate_limit() {
        let error = GatewayError::rate_limit("超出限流限制");
        
        assert_eq!(error.status_code(), StatusCode::TOO_MANY_REQUESTS);
        assert_eq!(error.error_code(), "GATEWAY_RATE_LIMIT");
        assert!(!error.is_retryable());
        
        match error {
            GatewayError::RateLimit { message, retry_after, rule_id } => {
                assert_eq!(message, "超出限流限制");
                assert_eq!(retry_after, None);
                assert_eq!(rule_id, None);
            },
            _ => panic!("Expected RateLimit error"),
        }
    }

    #[test]
    fn test_gateway_error_routing() {
        let error = GatewayError::routing("路由不存在", "/api/nonexistent");
        
        assert_eq!(error.status_code(), StatusCode::NOT_FOUND);
        assert_eq!(error.error_code(), "GATEWAY_ROUTING_ERROR");
        assert!(!error.is_retryable());
        
        match error {
            GatewayError::Routing { message, path } => {
                assert_eq!(message, "路由不存在");
                assert_eq!(path, "/api/nonexistent");
            },
            _ => panic!("Expected Routing error"),
        }
    }

    #[test]
    fn test_gateway_error_service_discovery() {
        let error = GatewayError::service_discovery("服务发现失败", "user-service");
        
        assert_eq!(error.status_code(), StatusCode::SERVICE_UNAVAILABLE);
        assert_eq!(error.error_code(), "GATEWAY_SERVICE_DISCOVERY_ERROR");
        assert!(error.is_retryable());
        
        match error {
            GatewayError::ServiceDiscovery { message, service_name } => {
                assert_eq!(message, "服务发现失败");
                assert_eq!(service_name, "user-service");
            },
            _ => panic!("Expected ServiceDiscovery error"),
        }
    }

    #[test]
    fn test_gateway_error_load_balance() {
        let error = GatewayError::load_balance("负载均衡失败", "order-service");
        
        assert_eq!(error.status_code(), StatusCode::SERVICE_UNAVAILABLE);
        assert_eq!(error.error_code(), "GATEWAY_LOAD_BALANCE_ERROR");
        assert!(error.is_retryable());
        
        match error {
            GatewayError::LoadBalance { message, service_name } => {
                assert_eq!(message, "负载均衡失败");
                assert_eq!(service_name, "order-service");
            },
            _ => panic!("Expected LoadBalance error"),
        }
    }

    #[test]
    fn test_gateway_error_network() {
        let error = GatewayError::network("网络连接失败", crate::core::NetworkErrorType::Connection);
        
        assert_eq!(error.status_code(), StatusCode::BAD_GATEWAY);
        assert_eq!(error.error_code(), "GATEWAY_NETWORK_ERROR");
        assert!(error.is_retryable());
        
        match error {
            GatewayError::Network { message, error_type } => {
                assert_eq!(message, "网络连接失败");
                match error_type {
                    crate::core::NetworkErrorType::Connection => {},
                    _ => panic!("Expected Connection error type"),
                }
            },
            _ => panic!("Expected Network error"),
        }
    }

    #[test]
    fn test_gateway_error_configuration() {
        let error = GatewayError::configuration("配置错误");
        
        assert_eq!(error.status_code(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(error.error_code(), "GATEWAY_CONFIG_ERROR");
        assert!(!error.is_retryable());
        
        match error {
            GatewayError::Configuration { message, config_key } => {
                assert_eq!(message, "配置错误");
                assert_eq!(config_key, None);
            },
            _ => panic!("Expected Configuration error"),
        }
    }

    #[test]
    fn test_gateway_error_validation() {
        let error = GatewayError::validation("参数验证失败");
        
        assert_eq!(error.status_code(), StatusCode::BAD_REQUEST);
        assert_eq!(error.error_code(), "GATEWAY_VALIDATION_ERROR");
        assert!(!error.is_retryable());
        
        match error {
            GatewayError::Validation { message, field } => {
                assert_eq!(message, "参数验证失败");
                assert_eq!(field, None);
            },
            _ => panic!("Expected Validation error"),
        }
    }

    #[test]
    fn test_gateway_error_internal() {
        let error = GatewayError::internal("内部错误");
        
        assert_eq!(error.status_code(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(error.error_code(), "GATEWAY_INTERNAL_ERROR");
        assert!(!error.is_retryable());
        
        match error {
            GatewayError::Internal { message } => {
                assert_eq!(message, "内部错误");
            },
            _ => panic!("Expected Internal error"),
        }
    }

    #[test]
    fn test_gateway_error_timeout() {
        let error = GatewayError::timeout("请求超时", 5000);
        
        assert_eq!(error.status_code(), StatusCode::GATEWAY_TIMEOUT);
        assert_eq!(error.error_code(), "GATEWAY_TIMEOUT_ERROR");
        assert!(error.is_retryable());
        
        match error {
            GatewayError::Timeout { message, timeout_ms } => {
                assert_eq!(message, "请求超时");
                assert_eq!(timeout_ms, 5000);
            },
            _ => panic!("Expected Timeout error"),
        }
    }

    #[test]
    fn test_network_error_types() {
        let connection_error = GatewayError::network("连接失败", crate::core::NetworkErrorType::Connection);
        let dns_error = GatewayError::network("DNS解析失败", crate::core::NetworkErrorType::DnsResolution);
        let timeout_error = GatewayError::network("连接超时", crate::core::NetworkErrorType::Timeout);
        let protocol_error = GatewayError::network("协议错误", crate::core::NetworkErrorType::Protocol);
        let other_error = GatewayError::network("其他错误", crate::core::NetworkErrorType::Other);
        
        // 所有网络错误都应该是可重试的
        assert!(connection_error.is_retryable());
        assert!(dns_error.is_retryable());
        assert!(timeout_error.is_retryable());
        assert!(protocol_error.is_retryable());
        assert!(other_error.is_retryable());
    }

    #[test]
    fn test_gateway_error_display() {
        let error = GatewayError::authentication("认证失败");
        let display_str = format!("{}", error);
        assert_eq!(display_str, "GATEWAY_AUTH_ERROR: 认证失败");
    }

    #[test]
    fn test_gateway_error_std_error_trait() {
        let error = GatewayError::internal("内部错误");
        
        // 验证实现了 std::error::Error trait
        let error_trait: &dyn std::error::Error = &error;
        assert!(error_trait.source().is_none());
    }

    #[test]
    fn test_gateway_error_from_io_error() {
        let io_error = std::io::Error::new(std::io::ErrorKind::ConnectionRefused, "连接被拒绝");
        let gateway_error = GatewayError::from(io_error);
        
        match gateway_error {
            GatewayError::Network { message, error_type } => {
                assert!(message.contains("IO错误"));
                match error_type {
                    crate::core::NetworkErrorType::Other => {},
                    _ => panic!("Expected Other error type"),
                }
            },
            _ => panic!("Expected Network error"),
        }
    }

    #[test]
    fn test_gateway_error_from_serde_json_error() {
        let json_str = "{ invalid json ";
        let json_error: serde_json::Error = serde_json::from_str::<serde_json::Value>(json_str).unwrap_err();
        let gateway_error = GatewayError::from(json_error);
        
        match gateway_error {
            GatewayError::Validation { message, field: _ } => {
                assert!(message.contains("JSON解析错误"));
            },
            _ => panic!("Expected Validation error"),
        }
    }

    #[test]
    fn test_gateway_error_from_tokio_timeout() {
        use tokio::time::{timeout, Duration};
        
        let rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async {
            let timeout_error = timeout(Duration::from_millis(1), async {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }).await.unwrap_err();
            
            let gateway_error = GatewayError::from(timeout_error);
            
            match gateway_error {
                GatewayError::Timeout { message, timeout_ms } => {
                    assert!(message.contains("操作超时"));
                    assert_eq!(timeout_ms, 30000);
                },
                _ => panic!("Expected Timeout error"),
            }
        });
    }

    #[test]
    fn test_gateway_error_is_retryable_classification() {
        // 不可重试的错误
        assert!(!GatewayError::authentication("认证失败").is_retryable());
        assert!(!GatewayError::authorization("授权失败").is_retryable());
        assert!(!GatewayError::rate_limit("限流").is_retryable());
        assert!(!GatewayError::routing("路由错误", "/test").is_retryable());
        assert!(!GatewayError::configuration("配置错误").is_retryable());
        assert!(!GatewayError::validation("验证错误").is_retryable());
        assert!(!GatewayError::internal("内部错误").is_retryable());
        
        // 可重试的错误
        assert!(GatewayError::service_discovery("服务发现失败", "test").is_retryable());
        assert!(GatewayError::load_balance("负载均衡失败", "test").is_retryable());
        assert!(GatewayError::network("网络错误", crate::core::NetworkErrorType::Connection).is_retryable());
        assert!(GatewayError::timeout("超时", 5000).is_retryable());
    }

    #[test]
    fn test_gateway_error_clone() {
        let original = GatewayError::authentication("认证失败");
        let cloned = original.clone();
        
        assert_eq!(original.message(), cloned.message());
        assert_eq!(original.error_code(), cloned.error_code());
        assert_eq!(original.status_code(), cloned.status_code());
    }

    // =============================================================================
    // Config 模块测试 - 第一部分：基础配置
    // =============================================================================

    #[test]
    fn test_gateway_config_default() {
        let config = GatewayConfig::default();
        
        // 验证默认值
        assert_eq!(config.server.host, "0.0.0.0");
        assert_eq!(config.server.port, 8080);
        assert_eq!(config.routing.default_timeout, 30000);
        assert!(!config.auth.enabled);
        assert!(!config.rate_limit.enabled);
        assert_eq!(config.service_discovery.discovery_type, "consul");
        assert_eq!(config.load_balance.strategy, "round_robin");
        assert!(config.monitoring.enabled);
        assert_eq!(config.logging.level, "info");
    }

    #[test]
    fn test_gateway_config_serialization() {
        let config = GatewayConfig::default();
        
        // 测试序列化
        let json_str = serde_json::to_string(&config);
        assert!(json_str.is_ok());
        
        // 测试反序列化
        let deserialized: Result<GatewayConfig, _> = serde_json::from_str(&json_str.unwrap());
        assert!(deserialized.is_ok());
        
        let deserialized_config = deserialized.unwrap();
        assert_eq!(config.server.host, deserialized_config.server.host);
        assert_eq!(config.server.port, deserialized_config.server.port);
    }

    #[test]
    fn test_server_config_default() {
        let config = ServerConfig::default();
        
        assert_eq!(config.host, "0.0.0.0");
        assert_eq!(config.port, 8080);
        assert_eq!(config.max_connections, Some(1000));
        assert_eq!(config.request_timeout, 30);
        assert_eq!(config.keep_alive_timeout, 60);
        assert!(!config.enable_https);
        assert!(config.tls.is_none());
    }

    #[test]
    fn test_server_config_with_https() {
        let mut config = ServerConfig::default();
        config.enable_https = true;
        config.tls = Some(TlsConfig {
            cert_file: "/path/to/cert.pem".to_string(),
            key_file: "/path/to/key.pem".to_string(),
            ca_file: Some("/path/to/ca.pem".to_string()),
        });
        
        assert!(config.enable_https);
        assert!(config.tls.is_some());
        
        let tls_config = config.tls.unwrap();
        assert_eq!(tls_config.cert_file, "/path/to/cert.pem");
        assert_eq!(tls_config.key_file, "/path/to/key.pem");
        assert_eq!(tls_config.ca_file, Some("/path/to/ca.pem".to_string()));
    }

    #[test]
    fn test_server_config_custom_values() {
        let config = ServerConfig {
            host: "127.0.0.1".to_string(),
            port: 9090,
            max_connections: Some(2000),
            request_timeout: 60,
            keep_alive_timeout: 120,
            enable_https: true,
            tls: None,
        };
        
        assert_eq!(config.host, "127.0.0.1");
        assert_eq!(config.port, 9090);
        assert_eq!(config.max_connections, Some(2000));
        assert_eq!(config.request_timeout, 60);
        assert_eq!(config.keep_alive_timeout, 120);
        assert!(config.enable_https);
    }

    #[test]
    fn test_tls_config() {
        let tls_config = TlsConfig {
            cert_file: "/etc/ssl/certs/server.crt".to_string(),
            key_file: "/etc/ssl/private/server.key".to_string(),
            ca_file: Some("/etc/ssl/certs/ca.crt".to_string()),
        };
        
        assert_eq!(tls_config.cert_file, "/etc/ssl/certs/server.crt");
        assert_eq!(tls_config.key_file, "/etc/ssl/private/server.key");
        assert_eq!(tls_config.ca_file, Some("/etc/ssl/certs/ca.crt".to_string()));
    }

    #[test]
    fn test_tls_config_without_ca() {
        let tls_config = TlsConfig {
            cert_file: "/path/to/cert.pem".to_string(),
            key_file: "/path/to/key.pem".to_string(),
            ca_file: None,
        };
        
        assert!(tls_config.ca_file.is_none());
    }

    #[test]
    fn test_routing_config_default() {
        let config = RoutingConfig::default();
        
        assert!(config.routes.is_empty());
        assert_eq!(config.default_timeout, 30000);
        assert!(config.enable_path_rewrite);
        assert!(config.enable_request_transform);
    }

    #[test]
    fn test_routing_config_with_routes() {
        let route_rule = RouteRule {
            id: "user-service-route".to_string(),
            path_pattern: "/api/users/*".to_string(),
            methods: vec!["GET".to_string(), "POST".to_string()],
            target_service: "user-service".to_string(),
            path_rewrite: Some("/users".to_string()),
            header_transforms: vec![
                HeaderTransform {
                    action: HeaderAction::Add,
                    name: "X-Service".to_string(),
                    value: Some("user-service".to_string()),
                },
            ],
            timeout: Some(5000),
            retry_count: Some(3),
        };
        
        let config = RoutingConfig {
            routes: vec![route_rule],
            default_timeout: 45000,
            enable_path_rewrite: false,
            enable_request_transform: false,
        };
        
        assert_eq!(config.routes.len(), 1);
        assert_eq!(config.default_timeout, 45000);
        assert!(!config.enable_path_rewrite);
        assert!(!config.enable_request_transform);
        
        let route = &config.routes[0];
        assert_eq!(route.id, "user-service-route");
        assert_eq!(route.path_pattern, "/api/users/*");
        assert_eq!(route.methods.len(), 2);
        assert_eq!(route.target_service, "user-service");
        assert_eq!(route.path_rewrite, Some("/users".to_string()));
        assert_eq!(route.header_transforms.len(), 1);
        assert_eq!(route.timeout, Some(5000));
        assert_eq!(route.retry_count, Some(3));
    }

    #[test]
    fn test_route_rule_minimal() {
        let route = RouteRule {
            id: "simple-route".to_string(),
            path_pattern: "/health".to_string(),
            methods: vec!["GET".to_string()],
            target_service: "health-service".to_string(),
            path_rewrite: None,
            header_transforms: vec![],
            timeout: None,
            retry_count: None,
        };
        
        assert_eq!(route.id, "simple-route");
        assert_eq!(route.path_pattern, "/health");
        assert_eq!(route.methods, vec!["GET".to_string()]);
        assert_eq!(route.target_service, "health-service");
        assert!(route.path_rewrite.is_none());
        assert!(route.header_transforms.is_empty());
        assert!(route.timeout.is_none());
        assert!(route.retry_count.is_none());
    }

    #[test]
    fn test_header_transform_actions() {
        let add_transform = HeaderTransform {
            action: HeaderAction::Add,
            name: "X-Custom-Header".to_string(),
            value: Some("custom-value".to_string()),
        };
        
        let set_transform = HeaderTransform {
            action: HeaderAction::Set,
            name: "User-Agent".to_string(),
            value: Some("Gateway/1.0".to_string()),
        };
        
        let remove_transform = HeaderTransform {
            action: HeaderAction::Remove,
            name: "X-Old-Header".to_string(),
            value: None,
        };
        
        // 验证 Add 操作
        match add_transform.action {
            HeaderAction::Add => assert_eq!(add_transform.value, Some("custom-value".to_string())),
            _ => panic!("Expected Add action"),
        }
        
        // 验证 Set 操作
        match set_transform.action {
            HeaderAction::Set => assert_eq!(set_transform.value, Some("Gateway/1.0".to_string())),
            _ => panic!("Expected Set action"),
        }
        
        // 验证 Remove 操作
        match remove_transform.action {
            HeaderAction::Remove => assert!(remove_transform.value.is_none()),
            _ => panic!("Expected Remove action"),
        }
    }

    // =============================================================================
    // Config 模块测试 - 第二部分：认证和限流配置
    // =============================================================================

    #[test]
    fn test_auth_config_default() {
        let config = AuthConfig::default();
        
        assert!(!config.enabled);
        assert!(config.providers.is_empty());
        assert!(config.jwt.is_none());
        assert!(config.api_key.is_none());
        assert!(config.basic_auth.is_none());
    }

    #[test]
    fn test_auth_config_with_jwt() {
        let jwt_config = JwtConfig {
            secret: "my-secret-key".to_string(),
            algorithm: "HS256".to_string(),
            expiration: 3600,
            issuer: Some("my-gateway".to_string()),
            audience: Some("my-api".to_string()),
        };
        
        let config = AuthConfig {
            enabled: true,
            providers: vec![],
            jwt: Some(jwt_config),
            api_key: None,
            basic_auth: None,
        };
        
        assert!(config.enabled);
        assert!(config.jwt.is_some());
        
        let jwt = config.jwt.unwrap();
        assert_eq!(jwt.secret, "my-secret-key");
        assert_eq!(jwt.algorithm, "HS256");
        assert_eq!(jwt.expiration, 3600);
        assert_eq!(jwt.issuer, Some("my-gateway".to_string()));
        assert_eq!(jwt.audience, Some("my-api".to_string()));
    }

    #[test]
    fn test_auth_config_with_api_key() {
        let api_key_config = ApiKeyConfig {
            header_name: "X-API-Key".to_string(),
            query_param: Some("apikey".to_string()),
            valid_keys: vec!["key1".to_string(), "key2".to_string()],
        };
        
        let config = AuthConfig {
            enabled: true,
            providers: vec![],
            jwt: None,
            api_key: Some(api_key_config),
            basic_auth: None,
        };
        
        assert!(config.enabled);
        assert!(config.api_key.is_some());
        
        let api_key = config.api_key.unwrap();
        assert_eq!(api_key.header_name, "X-API-Key");
        assert_eq!(api_key.query_param, Some("apikey".to_string()));
        assert_eq!(api_key.valid_keys.len(), 2);
        assert!(api_key.valid_keys.contains(&"key1".to_string()));
        assert!(api_key.valid_keys.contains(&"key2".to_string()));
    }

    #[test]
    fn test_auth_config_with_basic_auth() {
        let mut credentials = HashMap::new();
        credentials.insert("admin".to_string(), "password123".to_string());
        credentials.insert("user".to_string(), "userpass".to_string());
        
        let basic_auth_config = BasicAuthConfig {
            credentials,
            realm: "My API Gateway".to_string(),
        };
        
        let config = AuthConfig {
            enabled: true,
            providers: vec![],
            jwt: None,
            api_key: None,
            basic_auth: Some(basic_auth_config),
        };
        
        assert!(config.enabled);
        assert!(config.basic_auth.is_some());
        
        let basic_auth = config.basic_auth.unwrap();
        assert_eq!(basic_auth.realm, "My API Gateway");
        assert_eq!(basic_auth.credentials.len(), 2);
        assert_eq!(basic_auth.credentials.get("admin"), Some(&"password123".to_string()));
        assert_eq!(basic_auth.credentials.get("user"), Some(&"userpass".to_string()));
    }

    #[test]
    fn test_auth_provider() {
        let mut provider_config = HashMap::new();
        provider_config.insert("endpoint".to_string(), "https://auth.example.com".to_string());
        provider_config.insert("client_id".to_string(), "my-client-id".to_string());
        
        let provider = AuthProvider {
            name: "oauth2-provider".to_string(),
            provider_type: "oauth2".to_string(),
            config: provider_config,
            enabled: true,
        };
        
        assert_eq!(provider.name, "oauth2-provider");
        assert_eq!(provider.provider_type, "oauth2");
        assert!(provider.enabled);
        assert_eq!(provider.config.len(), 2);
        assert_eq!(provider.config.get("endpoint"), Some(&"https://auth.example.com".to_string()));
        assert_eq!(provider.config.get("client_id"), Some(&"my-client-id".to_string()));
    }

    #[test]
    fn test_rate_limit_config_default() {
        let config = RateLimitConfig::default();
        
        assert!(!config.enabled);
        assert!(config.global.is_none());
        assert!(config.per_service.is_empty());
        assert!(config.per_user.is_none());
        assert!(config.per_ip.is_none());
    }

    #[test]
    fn test_rate_limit_config_with_global_rule() {
        let global_rule = RateLimitRule {
            requests: 1000,
            window: 60,
            burst: Some(100),
        };
        
        let config = RateLimitConfig {
            enabled: true,
            global: Some(global_rule),
            per_service: HashMap::new(),
            per_user: None,
            per_ip: None,
        };
        
        assert!(config.enabled);
        assert!(config.global.is_some());
        
        let rule = config.global.unwrap();
        assert_eq!(rule.requests, 1000);
        assert_eq!(rule.window, 60);
        assert_eq!(rule.burst, Some(100));
    }

    #[test]
    fn test_rate_limit_config_with_per_service_rules() {
        let mut per_service = HashMap::new();
        per_service.insert("user-service".to_string(), RateLimitRule {
            requests: 500,
            window: 60,
            burst: None,
        });
        per_service.insert("order-service".to_string(), RateLimitRule {
            requests: 200,
            window: 60,
            burst: Some(20),
        });
        
        let config = RateLimitConfig {
            enabled: true,
            global: None,
            per_service,
            per_user: None,
            per_ip: None,
        };
        
        assert!(config.enabled);
        assert_eq!(config.per_service.len(), 2);
        
        let user_service_rule = config.per_service.get("user-service").unwrap();
        assert_eq!(user_service_rule.requests, 500);
        assert_eq!(user_service_rule.window, 60);
        assert!(user_service_rule.burst.is_none());
        
        let order_service_rule = config.per_service.get("order-service").unwrap();
        assert_eq!(order_service_rule.requests, 200);
        assert_eq!(order_service_rule.window, 60);
        assert_eq!(order_service_rule.burst, Some(20));
    }

    #[test]
    fn test_rate_limit_rule() {
        let rule = RateLimitRule {
            requests: 100,
            window: 3600,
            burst: Some(10),
        };
        
        assert_eq!(rule.requests, 100);
        assert_eq!(rule.window, 3600);
        assert_eq!(rule.burst, Some(10));
    }

    #[test]
    fn test_rate_limit_rule_without_burst() {
        let rule = RateLimitRule {
            requests: 50,
            window: 300,
            burst: None,
        };
        
        assert_eq!(rule.requests, 50);
        assert_eq!(rule.window, 300);
        assert!(rule.burst.is_none());
    }

    // =============================================================================
    // Config 模块测试 - 第三部分：服务发现和负载均衡配置
    // =============================================================================

    #[test]
    fn test_service_discovery_config_default() {
        let config = ServiceDiscoveryConfig::default();
        
        assert_eq!(config.discovery_type, "consul");
        assert_eq!(config.registry_urls, vec!["http://localhost:8500".to_string()]);
        assert!(config.namespace.is_none());
        assert_eq!(config.refresh_interval, 30);
        assert_eq!(config.health_check_interval, 10);
        assert_eq!(config.connection_timeout, 5000);
    }

    #[test]
    fn test_service_discovery_config_custom() {
        let config = ServiceDiscoveryConfig {
            discovery_type: "eureka".to_string(),
            registry_urls: vec![
                "http://eureka1:8761".to_string(),
                "http://eureka2:8761".to_string(),
            ],
            namespace: Some("production".to_string()),
            refresh_interval: 60,
            health_check_interval: 15,
            connection_timeout: 10000,
        };
        
        assert_eq!(config.discovery_type, "eureka");
        assert_eq!(config.registry_urls.len(), 2);
        assert!(config.registry_urls.contains(&"http://eureka1:8761".to_string()));
        assert!(config.registry_urls.contains(&"http://eureka2:8761".to_string()));
        assert_eq!(config.namespace, Some("production".to_string()));
        assert_eq!(config.refresh_interval, 60);
        assert_eq!(config.health_check_interval, 15);
        assert_eq!(config.connection_timeout, 10000);
    }

    #[test]
    fn test_load_balance_config_default() {
        let config = LoadBalanceConfig::default();
        
        assert_eq!(config.strategy, "round_robin");
        assert!(config.health_check.enabled);
        assert!(config.failover.enabled);
    }

    #[test]
    fn test_health_check_config_default() {
        let config = HealthCheckConfig::default();
        
        assert!(config.enabled);
        assert_eq!(config.path, "/health");
        assert_eq!(config.interval, 30);
        assert_eq!(config.timeout, 5000);
        assert_eq!(config.healthy_threshold, 2);
        assert_eq!(config.unhealthy_threshold, 3);
    }

    #[test]
    fn test_health_check_config_custom() {
        let config = HealthCheckConfig {
            enabled: false,
            path: "/api/health".to_string(),
            interval: 60,
            timeout: 10000,
            healthy_threshold: 3,
            unhealthy_threshold: 5,
        };
        
        assert!(!config.enabled);
        assert_eq!(config.path, "/api/health");
        assert_eq!(config.interval, 60);
        assert_eq!(config.timeout, 10000);
        assert_eq!(config.healthy_threshold, 3);
        assert_eq!(config.unhealthy_threshold, 5);
    }

    #[test]
    fn test_failover_config_default() {
        let config = FailoverConfig::default();
        
        assert!(config.enabled);
        assert_eq!(config.max_retries, 3);
        assert_eq!(config.retry_interval, 1000);
        assert!(config.circuit_breaker.is_none());
    }

    #[test]
    fn test_failover_config_with_circuit_breaker() {
        let circuit_breaker = CircuitBreakerConfig {
            failure_threshold: 50.0,
            time_window: 60,
            min_requests: 10,
            half_open_max_calls: 5,
        };
        
        let config = FailoverConfig {
            enabled: true,
            max_retries: 5,
            retry_interval: 2000,
            circuit_breaker: Some(circuit_breaker),
        };
        
        assert!(config.enabled);
        assert_eq!(config.max_retries, 5);
        assert_eq!(config.retry_interval, 2000);
        assert!(config.circuit_breaker.is_some());
        
        let cb = config.circuit_breaker.unwrap();
        assert_eq!(cb.failure_threshold, 50.0);
        assert_eq!(cb.time_window, 60);
        assert_eq!(cb.min_requests, 10);
        assert_eq!(cb.half_open_max_calls, 5);
    }

    #[test]
    fn test_circuit_breaker_config() {
        let config = CircuitBreakerConfig {
            failure_threshold: 75.5,
            time_window: 120,
            min_requests: 20,
            half_open_max_calls: 3,
        };
        
        assert_eq!(config.failure_threshold, 75.5);
        assert_eq!(config.time_window, 120);
        assert_eq!(config.min_requests, 20);
        assert_eq!(config.half_open_max_calls, 3);
    }

    #[test]
    fn test_middleware_config_default() {
        let config = MiddlewareConfig::default();
        
        assert!(config.middlewares.is_empty());
        assert!(config.enable_request_id);
        assert!(config.enable_access_log);
        assert!(!config.enable_cors);
        assert!(config.cors.is_none());
    }

    #[test]
    fn test_middleware_config_with_middlewares() {
        let mut middleware_config = HashMap::new();
        middleware_config.insert("timeout".to_string(), "30000".to_string());
        
        let middleware_def = MiddlewareDefinition {
            name: "timeout-middleware".to_string(),
            enabled: true,
            priority: 100,
            config: middleware_config,
        };
        
        let config = MiddlewareConfig {
            middlewares: vec![middleware_def],
            enable_request_id: false,
            enable_access_log: false,
            enable_cors: true,
            cors: None,
        };
        
        assert_eq!(config.middlewares.len(), 1);
        assert!(!config.enable_request_id);
        assert!(!config.enable_access_log);
        assert!(config.enable_cors);
        
        let middleware = &config.middlewares[0];
        assert_eq!(middleware.name, "timeout-middleware");
        assert!(middleware.enabled);
        assert_eq!(middleware.priority, 100);
        assert_eq!(middleware.config.get("timeout"), Some(&"30000".to_string()));
    }

    #[test]
    fn test_middleware_definition() {
        let mut config = HashMap::new();
        config.insert("max_size".to_string(), "10MB".to_string());
        config.insert("allowed_types".to_string(), "application/json,text/plain".to_string());
        
        let definition = MiddlewareDefinition {
            name: "body-limit".to_string(),
            enabled: false,
            priority: 50,
            config,
        };
        
        assert_eq!(definition.name, "body-limit");
        assert!(!definition.enabled);
        assert_eq!(definition.priority, 50);
        assert_eq!(definition.config.len(), 2);
        assert_eq!(definition.config.get("max_size"), Some(&"10MB".to_string()));
        assert_eq!(definition.config.get("allowed_types"), Some(&"application/json,text/plain".to_string()));
    }

    #[test]
    fn test_cors_config() {
        let config = CorsConfig {
            allowed_origins: vec!["https://example.com".to_string(), "https://app.example.com".to_string()],
            allowed_methods: vec!["GET".to_string(), "POST".to_string(), "PUT".to_string(), "DELETE".to_string()],
            allowed_headers: vec!["Content-Type".to_string(), "Authorization".to_string()],
            exposed_headers: vec!["X-Total-Count".to_string()],
            allow_credentials: true,
            max_age: 3600,
        };
        
        assert_eq!(config.allowed_origins.len(), 2);
        assert!(config.allowed_origins.contains(&"https://example.com".to_string()));
        assert!(config.allowed_origins.contains(&"https://app.example.com".to_string()));
        
        assert_eq!(config.allowed_methods.len(), 4);
        assert!(config.allowed_methods.contains(&"GET".to_string()));
        assert!(config.allowed_methods.contains(&"POST".to_string()));
        
        assert_eq!(config.allowed_headers.len(), 2);
        assert!(config.allowed_headers.contains(&"Content-Type".to_string()));
        assert!(config.allowed_headers.contains(&"Authorization".to_string()));
        
        assert_eq!(config.exposed_headers.len(), 1);
        assert!(config.exposed_headers.contains(&"X-Total-Count".to_string()));
        
        assert!(config.allow_credentials);
        assert_eq!(config.max_age, 3600);
    }

    // =============================================================================
    // Config 模块测试 - 第四部分：监控和日志配置
    // =============================================================================

    #[test]
    fn test_monitoring_config_default() {
        let config = MonitoringConfig::default();
        
        assert!(config.enabled);
        assert_eq!(config.metrics_interval, 60);
        assert_eq!(config.metrics_path, "/metrics");
        assert_eq!(config.health_path, "/health");
        assert!(config.prometheus.is_none());
    }

    #[test]
    fn test_monitoring_config_with_prometheus() {
        let prometheus_config = PrometheusConfig {
            enabled: true,
            push_gateway: Some("http://prometheus-pushgateway:9091".to_string()),
            job_name: "api-gateway".to_string(),
            push_interval: 30,
        };
        
        let config = MonitoringConfig {
            enabled: true,
            metrics_interval: 30,
            metrics_path: "/api/metrics".to_string(),
            health_path: "/api/health".to_string(),
            prometheus: Some(prometheus_config),
        };
        
        assert!(config.enabled);
        assert_eq!(config.metrics_interval, 30);
        assert_eq!(config.metrics_path, "/api/metrics");
        assert_eq!(config.health_path, "/api/health");
        assert!(config.prometheus.is_some());
        
        let prometheus = config.prometheus.unwrap();
        assert!(prometheus.enabled);
        assert_eq!(prometheus.push_gateway, Some("http://prometheus-pushgateway:9091".to_string()));
        assert_eq!(prometheus.job_name, "api-gateway");
        assert_eq!(prometheus.push_interval, 30);
    }

    #[test]
    fn test_prometheus_config() {
        let config = PrometheusConfig {
            enabled: false,
            push_gateway: None,
            job_name: "gateway-service".to_string(),
            push_interval: 60,
        };
        
        assert!(!config.enabled);
        assert!(config.push_gateway.is_none());
        assert_eq!(config.job_name, "gateway-service");
        assert_eq!(config.push_interval, 60);
    }

    #[test]
    fn test_logging_config_default() {
        let config = LoggingConfig::default();
        
        assert_eq!(config.level, "info");
        assert_eq!(config.format, "json");
        assert_eq!(config.output, vec!["stdout".to_string()]);
        assert!(config.file.is_none());
    }

    #[test]
    fn test_logging_config_with_file() {
        let file_config = LogFileConfig {
            path: "/var/log/gateway.log".to_string(),
            max_size: 100,
            max_files: 10,
            compress: true,
        };
        
        let config = LoggingConfig {
            level: "debug".to_string(),
            format: "text".to_string(),
            output: vec!["stdout".to_string(), "file".to_string()],
            file: Some(file_config),
        };
        
        assert_eq!(config.level, "debug");
        assert_eq!(config.format, "text");
        assert_eq!(config.output.len(), 2);
        assert!(config.output.contains(&"stdout".to_string()));
        assert!(config.output.contains(&"file".to_string()));
        assert!(config.file.is_some());
        
        let file = config.file.unwrap();
        assert_eq!(file.path, "/var/log/gateway.log");
        assert_eq!(file.max_size, 100);
        assert_eq!(file.max_files, 10);
        assert!(file.compress);
    }

    #[test]
    fn test_log_file_config() {
        let config = LogFileConfig {
            path: "/tmp/test.log".to_string(),
            max_size: 50,
            max_files: 5,
            compress: false,
        };
        
        assert_eq!(config.path, "/tmp/test.log");
        assert_eq!(config.max_size, 50);
        assert_eq!(config.max_files, 5);
        assert!(!config.compress);
    }

    #[test]
    fn test_config_serialization_roundtrip() {
        // 创建一个复杂的配置
        let mut config = GatewayConfig::default();
        config.server.port = 9090;
        config.auth.enabled = true;
        config.rate_limit.enabled = true;
        
        // 序列化
        let json_str = serde_json::to_string_pretty(&config).unwrap();
        
        // 反序列化
        let deserialized: GatewayConfig = serde_json::from_str(&json_str).unwrap();
        
        // 验证数据一致性
        assert_eq!(config.server.port, deserialized.server.port);
        assert_eq!(config.auth.enabled, deserialized.auth.enabled);
        assert_eq!(config.rate_limit.enabled, deserialized.rate_limit.enabled);
        assert_eq!(config.monitoring.enabled, deserialized.monitoring.enabled);
    }

    #[test]
    fn test_config_edge_cases() {
        // 测试空列表和空字符串
        let config = RoutingConfig {
            routes: vec![],
            default_timeout: 0,
            enable_path_rewrite: false,
            enable_request_transform: false,
        };
        
        assert!(config.routes.is_empty());
        assert_eq!(config.default_timeout, 0);
        
        // 测试空的认证提供者
        let auth_config = AuthConfig {
            enabled: true,
            providers: vec![],
            jwt: None,
            api_key: None,
            basic_auth: None,
        };
        
        assert!(auth_config.enabled);
        assert!(auth_config.providers.is_empty());
    }

    #[test]
    fn test_config_validation_scenarios() {
        // 测试有效的配置组合
        let config = GatewayConfig {
            server: ServerConfig {
                host: "127.0.0.1".to_string(),
                port: 8080,
                max_connections: Some(1000),
                request_timeout: 30,
                keep_alive_timeout: 60,
                enable_https: false,
                tls: None,
            },
            routing: RoutingConfig {
                routes: vec![],
                default_timeout: 30000,
                enable_path_rewrite: true,
                enable_request_transform: true,
            },
            auth: AuthConfig {
                enabled: false,
                providers: vec![],
                jwt: None,
                api_key: None,
                basic_auth: None,
            },
            rate_limit: RateLimitConfig {
                enabled: false,
                global: None,
                per_service: HashMap::new(),
                per_user: None,
                per_ip: None,
            },
            service_discovery: ServiceDiscoveryConfig::default(),
            load_balance: LoadBalanceConfig::default(),
            middleware: MiddlewareConfig::default(),
            monitoring: MonitoringConfig::default(),
            logging: LoggingConfig::default(),
        };
        
        // 验证配置的内在一致性
        assert_eq!(config.server.host, "127.0.0.1");
        assert!(!config.auth.enabled);
        assert!(!config.rate_limit.enabled);
        assert!(!config.server.enable_https);
        assert!(config.server.tls.is_none());
    }

    #[test]
    fn test_complex_config_scenario() {
        // 测试复杂的配置场景
        let mut per_service_limits = HashMap::new();
        per_service_limits.insert("api-service".to_string(), RateLimitRule {
            requests: 1000,
            window: 60,
            burst: Some(100),
        });
        
        let config = GatewayConfig {
            server: ServerConfig {
                host: "0.0.0.0".to_string(),
                port: 443,
                max_connections: Some(10000),
                request_timeout: 60,
                keep_alive_timeout: 300,
                enable_https: true,
                tls: Some(TlsConfig {
                    cert_file: "/etc/ssl/server.crt".to_string(),
                    key_file: "/etc/ssl/server.key".to_string(),
                    ca_file: None,
                }),
            },
            routing: RoutingConfig {
                routes: vec![RouteRule {
                    id: "api-route".to_string(),
                    path_pattern: "/api/**".to_string(),
                    methods: vec!["GET".to_string(), "POST".to_string()],
                    target_service: "api-service".to_string(),
                    path_rewrite: Some("/v1".to_string()),
                    header_transforms: vec![],
                    timeout: Some(30000),
                    retry_count: Some(3),
                }],
                default_timeout: 30000,
                enable_path_rewrite: true,
                enable_request_transform: true,
            },
            auth: AuthConfig {
                enabled: true,
                providers: vec![],
                jwt: Some(JwtConfig {
                    secret: "super-secret-key".to_string(),
                    algorithm: "HS256".to_string(),
                    expiration: 3600,
                    issuer: Some("api-gateway".to_string()),
                    audience: Some("api-clients".to_string()),
                }),
                api_key: None,
                basic_auth: None,
            },
            rate_limit: RateLimitConfig {
                enabled: true,
                global: Some(RateLimitRule {
                    requests: 10000,
                    window: 60,
                    burst: Some(1000),
                }),
                per_service: per_service_limits,
                per_user: None,
                per_ip: Some(RateLimitRule {
                    requests: 100,
                    window: 60,
                    burst: Some(10),
                }),
            },
            service_discovery: ServiceDiscoveryConfig {
                discovery_type: "consul".to_string(),
                registry_urls: vec!["http://consul:8500".to_string()],
                namespace: Some("production".to_string()),
                refresh_interval: 30,
                health_check_interval: 10,
                connection_timeout: 5000,
            },
            load_balance: LoadBalanceConfig {
                strategy: "weighted_round_robin".to_string(),
                health_check: HealthCheckConfig {
                    enabled: true,
                    path: "/health".to_string(),
                    interval: 30,
                    timeout: 5000,
                    healthy_threshold: 2,
                    unhealthy_threshold: 3,
                },
                failover: FailoverConfig {
                    enabled: true,
                    max_retries: 3,
                    retry_interval: 1000,
                    circuit_breaker: Some(CircuitBreakerConfig {
                        failure_threshold: 50.0,
                        time_window: 60,
                        min_requests: 10,
                        half_open_max_calls: 5,
                    }),
                },
            },
            middleware: MiddlewareConfig {
                middlewares: vec![],
                enable_request_id: true,
                enable_access_log: true,
                enable_cors: true,
                cors: Some(CorsConfig {
                    allowed_origins: vec!["*".to_string()],
                    allowed_methods: vec!["GET".to_string(), "POST".to_string(), "PUT".to_string(), "DELETE".to_string()],
                    allowed_headers: vec!["*".to_string()],
                    exposed_headers: vec![],
                    allow_credentials: false,
                    max_age: 3600,
                }),
            },
            monitoring: MonitoringConfig {
                enabled: true,
                metrics_interval: 60,
                metrics_path: "/metrics".to_string(),
                health_path: "/health".to_string(),
                prometheus: Some(PrometheusConfig {
                    enabled: true,
                    push_gateway: Some("http://prometheus:9091".to_string()),
                    job_name: "api-gateway".to_string(),
                    push_interval: 30,
                }),
            },
            logging: LoggingConfig {
                level: "info".to_string(),
                format: "json".to_string(),
                output: vec!["stdout".to_string(), "file".to_string()],
                file: Some(LogFileConfig {
                    path: "/var/log/gateway.log".to_string(),
                    max_size: 100,
                    max_files: 10,
                    compress: true,
                }),
            },
        };
        
        // 验证复杂配置的一致性
        assert!(config.server.enable_https);
        assert!(config.server.tls.is_some());
        assert!(config.auth.enabled);
        assert!(config.auth.jwt.is_some());
        assert!(config.rate_limit.enabled);
        assert!(config.rate_limit.global.is_some());
        assert!(config.rate_limit.per_ip.is_some());
        assert_eq!(config.service_discovery.namespace, Some("production".to_string()));
        assert_eq!(config.load_balance.strategy, "weighted_round_robin");
        assert!(config.load_balance.failover.circuit_breaker.is_some());
        assert!(config.monitoring.prometheus.is_some());
        assert!(config.logging.file.is_some());
        
        // 验证可以正常序列化和反序列化
        let json_result = serde_json::to_string(&config);
        assert!(json_result.is_ok());
        
        let deserialized_result: Result<GatewayConfig, _> = serde_json::from_str(&json_result.unwrap());
        assert!(deserialized_result.is_ok());
    }
}